<template>
  <div
    class="jcyqm"
    v-loading.fullscreen.lock="fullscreenLoading"
    :element-loading-text="loadingText"
  >
    <img :src="qmtp" ref="jcyqmRef" class="jcyqm-img" />
  </div>
</template>

<script lang="ts" setup>
import sign from './hw-socket'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
// const emits = defineEmits(['getQmtp'])
const fullscreenLoading = ref(false)
const loadingText = ref('')
// 签名图片base64地址
const qmtp = ref('')
const websocket = ref()
// 当前设备是否存在
const isDeviceExist = ref(false)
/**
 * 检察官签名
 */

onMounted(() => {
  /* 初始化 */
  // socketBegin()
})
onBeforeUnmount(() => {
  /* 清空socket */
  buttonClearSign()
  buttonFinalize()
  buttonDisConnnect()
  endsign()
})

const socketBegin = () => {
  loadingText.value = '签字板加载中...'
  qmtp.value = ''
  fullscreenLoading.value = true
  // 其他（国产化环境）
  sign.connectWebSocket((bol: boolean) => {
    // 初始化环境
    if (bol) {
      fullscreenLoading.value = false
      checkdevice()
    } else {
      fullscreenLoading.value = false
    }
  })
}
const checkdevice = () => {
  sign.getDeviceStatus((res: any) => {
    if (res.msgID !== 0) {
      // 获取当前设备状态
      ElMessage.error('汉王签字板状态异常，请检查设备是否正常连接！')
    } else {
      isDeviceExist.value = true
      let wndWidth = 600,
        wndHeight = 400
      let ratio = res.aspectRatio //获取签字板屏幕宽高比
      const resStrs = ratio.split(':')
      const aspectRatio = (resStrs[0] / resStrs[1]).toFixed(4)
      //设置程序签字窗口宽高，与签字板宽高比保持一致，防止笔迹失真
      ratio = (wndWidth / wndHeight).toFixed(4)
      if (ratio > aspectRatio) {
        wndWidth = Math.round(wndHeight * aspectRatio)
      } else wndHeight = Math.round(wndWidth / aspectRatio)
      startsign(wndWidth, wndHeight)
    }
  })
}

/* 开始签字 */
const startsign = (wndWidth: number, wndHeight: number) => {
  if (!isDeviceExist.value) {
    checkdevice()
  } else {
    sign.startSign(
      (res: any) => {
        if (res.msgID === 0) {
          getsign()
        }
      },
      (window.screen.width - wndWidth) / 2,
      (window.screen.height - wndHeight) / 2 - 100,
      wndWidth,
      wndHeight,
      250,
      150,
      1,
      30,
    )
  }
}
/* 获取签字文件 */
const getsign = () => {
  sign.getSign(async (res: any) => {
    if (res.msgID === 0) {
      qmtp.value = res.message
      // const imageData = await base64DataURLToImageData(qmtp.value)
      // emits('getQmtp', {
      //   base64Url: qmtp.value,
      //   base64: res.message.split(',')[1],
      //   imageData: imageData,
      // })
    } else {
      console.log('获取签字文件失败')
    }
  })
}

/* 结束签字 */
const endsign = () => {
  sign?.endSign((res: any) => {
    if (res.msgID !== 0) {
      console.log('结束签字失败')
    }
  })
}

/**
 * base64回显
 */
const base64DataURLToImageData = (base64DataURL: string) => {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.onload = () => {
      const canvas = document.createElement('canvas')
      const context = canvas.getContext('2d')
      canvas.width = img.width
      canvas.height = img.height
      if (!context) {
        reject(new Error('context is null'))
        return
      }
      context.drawImage(img, 0, 0)
      const imageData = context.getImageData(0, 0, canvas.width, canvas.height)
      resolve(imageData)
    }
    img.onerror = (error) => {
      reject(error)
    }
    img.src = base64DataURL
  })
}

const buttonClearSign = () => {
  websocket.value?.send('{"HWPenSign":"HWClearSign"}')
}
const buttonFinalize = () => {
  websocket.value?.send('{"HWPenSign":"HWFinalize"}')
}
const buttonDisConnnect = () => {
  websocket.value?.close()
}

defineExpose({ qmtp, socketBegin })
</script>

<style lang="scss" scoped>
.jcyqm {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  .jcyqm-img {
    transform: scale(1.2);
  }
}
</style>
